<template>
  <div class="list-table">
    <div class=" area-header">
      <span class="area-header-title">{{ $t('基金角色管理') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('角色名称')" prop="roleName">
        <!--        <dict-select v-model="queryParams.roleKey" :placeholder="$t('角色名称')" clearable dictionary="fund_team_role" />-->
        <el-select v-model="queryParams.roleKey" :placeholder="$t('角色名称')" clearable>
          <el-option v-for="role in roleOptions" :key="role.id" :value="role.dictValue" :label="role.dictLabel" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('创建时间')">
        <DatePicker
          v-model="dateRange"
          type="daterange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:dealRole:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:dealRole:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >{{ $t('删除') }}</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roleList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('角色名称')" prop="roleName" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('创建时间')" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" width="350" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:dealRole:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['system:dealRole:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="$t('角色')" :visible.sync="open" width="70%" custom-class="roleDialog" :close-on-click-modal="false" :lock-scroll="false">
      <el-form ref="form" v-loading="loadingTree" :model="form" class="dataForm" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="8" style="display: block;">
            <el-form-item :label="$t('角色名称')" prop="roleKey">
              <!--              <dict-select v-model="form.roleKey" dictionary="deal_role" :placeholder="$t('角色名称')" />-->
              <el-select
                v-model="form.roleKey"
                filterable
                :clearable="true"
                :placeholder="$t('角色名称')"
                :no-data-text="$t('无数据')"
                :no-match-text="$t('无数据')"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.dictValue"
                  :label="$t(item.dictLabel)"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('备注')">
              <el-input v-model="form.remark" type="textarea" maxlength="200" show-word-limit="" :placeholder="$t('备注')" />
            </el-form-item>
          </el-col>
          <el-col v-loading="menuLoading" :span="16" style="display: block;">
            <el-tabs v-model="activeName">
              <el-tab-pane v-for="(v, index) in dealTypeOptions" :key="index" :label="$t(v.dictLabel)" :name="v.dictValue">
                <div style="border: 1px solid #eee;padding: 10px;height: 100%;">
                  <Ztree ref="Ztree" menu="deal" :permissions-list="v.permissionsList" :menu-options="v.menuOptions" :check-nodes="checkNodes" :expand-all="true" @checkedDataDeal="checkedPC($event, index)" />
                </div>
              </el-tab-pane>
            </el-tabs>

          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("确定") }}</el-button>
        <el-button @click="cancel">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { exportRole, dataScope, changeRoleStatus } from '@/api/system/role'
import { treeselectAndPermissionByDeal } from '@/api/system/menu'
import Ztree from '@/components/Ztree/checkTree'
import {
  addDealRole, delDealRoles,
  getDealRole,
  listDealRole,
  updateDealRole
} from '@/api/system/dealRole/dealRole'
export default {
  name: 'Role',
  components: {
    Ztree
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      menuLoading: true,
      loadingTree: false,
      activeName: 'equity',
      roleId: '',
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 用户数组
      formData: [],
      toData: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 项目类型字典
      dealTypeOptions: [],
      // 菜单列表
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleKey: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dealCheckedKeys: {},
      roleOptions: [],
      // 表单校验
      rules: {
        roleKey: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
        ]
      },
      permissionsId: '',
      // 选中的节点
      checkNodes: [],
      permissionsList: []
    }
  },
  created() {
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('fund_team_role').then(res => {
      if (!res.data) {
        res.data = []
      }
      res.data.push({
        dictValue: 'N',
        dictLabel: '非基金成员'
      })
      this.roleOptions = res.data
    })
  },
  mounted() {
    this.getList()
    this.getDicts('fund_menu_type').then(response => {
      this.dealTypeOptions = response.data || []
      if (this.dealTypeOptions.length > 0) {
        this.dealTypeOptions.forEach(v => {
          treeselectAndPermissionByDeal('fund', { menuKey: v.dictValue }).then(ele => {
            var menuOptions = ele.data.deal || []
            this.permissionsList = []
            this.$set(v, 'menuOptions', menuOptions)
            this.getAllNode(v.menuOptions)
            this.$set(v, 'permissionsList', this.permissionsList)
          })
        })
      }
    })
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      this.queryParams.busType = 'fund'
      listDealRole(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.roleList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    getAllNode(list) {
      for (let i = 0; i < list.length; i++) {
        var item = list[i]
        this.$set(item, 'list', [])
        if (item.children) {
          var children = item.children.filter(v => v.type === 'menu')
          var lists = item.children.filter(v => v.type !== 'menu')
          this.permissionsList = this.permissionsList.concat(lists)
          this.$set(item, 'children', children)
          this.$set(item, 'list', lists)
          this.getAllNode(item.children)
        }
      }
      this.$forceUpdate()
    },
    checkedPC(val, index) { // 选中节点集合
      // console.log(val, index)
      this.dealCheckedKeys[index] = val
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.checkNodes = []
      this.activeName = 'fund_base'
      this.menuLoading = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = this.menuLoading = true
      this.reset()
      this.activeName = 'fund_base'
      const roleId = row.roleId || this.ids
      getDealRole(roleId).then(response => {
        this.form = response.data
        this.checkNodes = response.data.menusId || []
        this.menuLoading = false
      })
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      const checkedKeys = this.$refs.dept.getHalfCheckedKeys()
      // 半选中的部门节点
      const halfCheckedKeys = this.$refs.dept.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },

    // 角色状态修改f
    handleStatusChange(row) {
      const text = row.status === '0' ? this.$t('启用') : this.$t('停用')
      this.$confirm(this.$t('确认要') + text + ' ' + row.roleName + '?', this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return changeRoleStatus(row.roleId, row.status)
      }).then(() => {
        this.msgSuccess(text + this.$t('成功'))
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.dealCheckedKeys = {}
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        status: '0',
        menuIds: [],
        deptIds: [],
        remark: undefined,
        busType: 'fund'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      // console.log(this.ids)
      this.multiple = !selection.length
    },

    /** 提交按钮 */
    submitForm: function() {
      this.loadingTree = true
      setTimeout(() => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            var arr = []
            for (var i in this.dealCheckedKeys) {
              arr = arr.concat(this.dealCheckedKeys[i])
            }
            this.form.menusId = [...new Set(arr)]
            this.form.dealTypeList = this.dealTypeOptions.map(v => v.dictValue)
            if (this.form.roleId !== undefined) {
              updateDealRole(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('修改成功'))
                  this.open = false
                  this.loadingTree = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                  this.loadingTree = false
                }
              }).catch(() => {
                this.loadingTree = false
              })
            } else {
              addDealRole(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('添加成功'))
                  this.open = false
                  this.loadingTree = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                  this.loadingTree = false
                }
              }).catch(() => {
                this.loadingTree = false
              })
            }
          } else {
            this.locationError(document)
            this.loadingTree = false
          }
        })
      }, 1000)
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.roleId !== undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys()
        dataScope(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t('修改成功'))
            this.openDataScope = false
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId ? [row.roleId] : this.ids
      // console.log(roleIds)
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delDealRoles(roleIds)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {})
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('是否确认导出所有角色数据项?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return exportRole(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {})
    }
  }
}
</script>

